<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/backend' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>博文管理</el-breadcrumb-item>
      <el-breadcrumb-item>编辑博文</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片 -->
    <el-card class="box-card">
      <el-row :gutter="20">
        <el-col :span="10">
          <el-input
            placeholder="输入内容查找相似的标题或描述"
            class="input-with-select"
            v-model="queryPosts.query"
            clearable
            @change="getPostsList"
          >
            <el-button slot="append" icon="el-icon-search" @click="getPostsList"></el-button>
          </el-input>
        </el-col>
        <el-col :span="6">
          <el-button type="primary" @click="dialogFormVisible = true">添加文章</el-button>
          <el-dialog title="添加文章" :visible.sync="dialogFormVisible">
            <el-form :model="Posts" :rules="rules" ref="Posts" label-width="100px" class="Posts-form">
              <el-form-item label="文章标题" prop="title">
                <el-input v-model="Posts.title"></el-input>
              </el-form-item>
              <el-form-item label="文章描述" prop="describe">
                <el-input v-model="Posts.describe"></el-input>
              </el-form-item>
              <el-form-item label="标签" prop="Sort_id">
                <el-select v-model="Posts.Sort_id" placeholder="请选择标签">
                  <el-option v-for="stItem in sorts" :key="stItem.ctItem" :label="stItem.sortName" :value="stItem.sort_id"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="类别" prop="contentSort_id">
                <el-select v-model="Posts.contentSort_id" placeholder="请选择类别">
                  <el-option v-for="ctItem in contnetSorts" :key="ctItem.consort_id" :label="ctItem.ctName" :value="ctItem.consort_id"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="内容" prop="content">
                <el-input type="textarea" :rows="5"  v-model="Posts.content"></el-input>
              </el-form-item>
              <el-form-item>
                <el-button type="primary" @click="submitForm('Posts')">发布</el-button>
                <el-button @click="resetForm('Posts')">重置</el-button>
              </el-form-item>
            </el-form>
          </el-dialog>
          </el-col>
      </el-row>
      <el-table stripe border :data="postsList" height="350" >
        <!-- <el-table-column type="selection" width="40"></el-table-column> -->
        <el-table-column type="index" label="编号"></el-table-column>
        <el-table-column prop="title" label="标题" width="200"></el-table-column>
        <el-table-column prop="describes" label="描述" width="180"></el-table-column>
        <el-table-column prop="content" label="内容" width="200"></el-table-column>
         <!-- :show-overflow-tooltip="true" -->
        <el-table-column prop="data_time" label="日期" width="200"></el-table-column>
        <el-table-column prop="img" label="图片" width="200"></el-table-column>
        <el-table-column prop="sortName" label="标签" width="100"></el-table-column>
        <el-table-column prop="ctName" label="分类"  width="100"></el-table-column>
        <el-table-column prop="readAmount" label="阅读量"  width="65"></el-table-column>
        <el-table-column prop="dPraiseCount" label="点赞数"  width="65"></el-table-column>
        <el-table-column prop="dCollectCount" label="收藏数"  width="65"></el-table-column>
        <el-table-column prop label="操作" fixed="right" width="180">
          <template slot-scope="scope">
            <div>
              <!--修改-->
              <el-button type="primary" icon="el-icon-edit" circle @click="editOpen(scope.row)"></el-button>
              <!-- 弹出框，修改-->
              <el-dialog title="编辑用户" :visible.sync="deitFormVisible" :modal-append-to-body='false'>
                <el-form :model="editPosts" :rules="rules" ref="editPosts" label-width="100px" class="Posts-form">
                  <el-form-item label="文章标题" prop="title">
                    <el-input v-model="editPosts.title"></el-input>
                  </el-form-item>
                  <el-form-item label="文章描述" prop="describe">
                    <el-input v-model="editPosts.describes"></el-input>
                  </el-form-item>
                  <el-form-item label="标签" prop="Sort_id">
                    <el-select v-model="editPosts.Sort_id" placeholder="请选择标签">
                      <el-option v-for="stItem in sorts" :key="stItem.ctItem" :label="stItem.sortName" :value="stItem.sort_id"></el-option>
                    </el-select>
                  </el-form-item>
                  <el-form-item label="类别" prop="contentSort_id">
                    <el-select v-model="editPosts.contentSort_id" placeholder="请选择类别">
                      <el-option v-for="ctItem in contnetSorts" :key="ctItem.consort_id" :label="ctItem.ctName" :value="ctItem.consort_id"></el-option>
                    </el-select>
                  </el-form-item>
                  <el-form-item label="内容" prop="content">
                    <el-input type="textarea" :rows="5"  v-model="editPosts.content"></el-input>
                  </el-form-item>
                  <el-form-item>
                    <el-button type="primary" @click="edit(editPosts)">修改</el-button>
                    <el-button @click="resetForm('editPosts')">重置</el-button>
                  </el-form-item>
                </el-form>
              </el-dialog>
              <!--分配权限-->
              <el-button type="primary" icon="el-icon-s-tools" circle></el-button>
              <!--删除-->
              <el-button type="danger" icon="el-icon-delete" circle slot="reference"  @click="dialogVisible = true"></el-button>
              <el-dialog
                title="提示"
                :visible.sync="dialogVisible"
                width="30%"
                :before-close="handleClose"
                :modal-append-to-body='false'>
                <span>确定删除？</span>
                <span slot="footer" class="dialog-footer">
                  <el-button @click="dialogVisible = false">取 消</el-button>
                  <el-button type="primary" @click="del(scope.row.data_id)">确 定</el-button>
                </span>
              </el-dialog>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryPosts.pagenum"
        :page-sizes="[3, 5, 10, 100]"
        :page-size="queryPosts.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      ></el-pagination>
    </el-card>
  </div>
</template>
<script>
export default {
  data() {
    return {
      queryPosts: {
        query: "",
        pagenum: 1, //当前页码
        pagesize: 3 //每页显示条数
      },
      Posts: {
        title: '',
        describe:'',
        Sort_id:'',
        contentSort_id: '',
        content:'',
        time:'',
        img:'',
      },
      editPosts:{
        id:'',
        title: '',
        describe:'',
        Sort_id:'',
        contentSort_id: '',
        content:'',
        time:'',
        img:'',
      },
      sorts:[],
      contnetSorts:[],
      rules: {
        title: [
          { required: true, message: '请输入文章标题', trigger: 'blur' },
          { min: 1, max: 15, message: '长度在 1 到 15 个字符', trigger: 'blur' }
        ],
        describe: [
          { required: true, message: '请输入文章描述', trigger: 'blur' },
          { min: 0, max: 40, message: '长度在 0 到 40 个字符', trigger: 'blur' }
        ],
        Sort_id: [
          { required: true, message: '请选择活动区域', trigger: 'change' }
        ],
        contentSort_id: [
          { required: true, message: '请选择活动区域', trigger: 'change' }
        ],
        content: [
          { required: true, message: '请填写活动形式', trigger: 'blur' }
        ]
      },
      postsList: [],
      total: 0,
      dialogTableVisible: false,
      dialogFormVisible: false,//添加文章
      addUser: {
        username: "",
        password: "",
        email: "",
        mobile: ""
      },
      formLabelWidth: "120px",
      visible: false,
      dialogVisible: false,//删除文章
      deitFormVisible:false,//修改文章
      editForm:{
        id:"",
        rid:"",
        username: "",
        password: "",
        email: "",
        mobile: ""
      }
    };
  },
  created() {
    this.getSorts();
    this.getPostsList();
  },
  methods: {
    // 首先获取标签详情
    async getSorts(){
      const {data:sortRes} = await this.$http.get("getknowTags");
      // console.log(sortRes);
      if(sortRes.status != 200){
        this.$message.error('获取数据失败');
      }else{
        this.sorts = sortRes.message
      }
      const {data:contentRes} = await this.$http.get("getcontentTags");
      // console.log(contentRes);
      if(contentRes.status != 200){
        this.$message.error('获取数据失败');
      }else{
        this.contnetSorts = contentRes.message;
      }
    },
    // 添加文章按钮
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.Publish();
        } else {
          this.$message.error('error submit!!');
          return false;
        }
      });
    },
    // 添加文章
    async Publish(){
      this.dialogFormVisible = false;
      this.Posts.time = this.changeDate(new Date());
      let index = this.getRandom(1,20);
      this.Posts.img = "/static/img/avatar/"+index+".jpg"
      // console.log(this.Posts);
      let Posts = JSON.stringify(this.Posts);
      console.log(Posts);
      const {data:res} = await this.$http.post("insertPosts",{Posts});
      if(res.status != 200){
        this.$message.error('添加数据失败');
      }else{
        // console.log(res);
        this.$message({
          message: '发布成功',
          type: 'success'
        });
        this.getPostsList();
      }
    },
    // 重置
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    // 获取随机数
    getRandom(min, max){
      return Math.floor(Math.random() * (max - min + 1)) + min
    },
    // 转换时间格式
    changeDate(date){
      var y = date.getFullYear();
        var m = date.getMonth() + 1;
        m = m < 10 ? ('0' + m) : m;
        var d = date.getDate();
        d = d < 10 ? ('0' + d) : d;
        var h = date.getHours();
        h=h < 10 ? ('0' + h) : h;
        var minute = date.getMinutes();
        minute = minute < 10 ? ('0' + minute) : minute;
        var second=date.getSeconds();
        second=second < 10 ? ('0' + second) : second;
        return y + '-' + m + '-' + d+' '+h+':'+minute+':'+second;
    },
    // 获取指定数据
    async getPostsList() {
      let queryPosts = this.queryPosts;
      const {data:res} = await this.$http.post("selPostsDesc",{queryPosts});
      console.log(res);
     if (res.status !== 200) {
        this.$message.error("获取用户列表失败");
      } else {
        this.postsList = res.message;
        if(queryPosts.query ==""){
          const {data:totalRes} = await this.$http.get("getDataDesc");
          // console.log(totalRes.message.length);
          if(totalRes.status != 200){
          this.$message.error("获取用户列表失败");
          }else{
            this.total = totalRes.message.length;
          }
        }else{
          this.total = res.message.length;
        }
        // console.log(this.postsList);
      }
      this.queryPosts.query=""
    },
    // 每页条数
    handleSizeChange: function(newSize) {
      // console.log("newSize:"+newSize);
      this.queryPosts.pagesize = newSize;
      this.getPostsList();
    },
    // 第几页
    handleCurrentChange: function(current) {
      // console.log("current:"+current);
      this.queryPosts.pagenum = current;
      this.getPostsList();
    },
    // 修改按钮
    editOpen(item) {
      console.log(item);
      this.deitFormVisible=true;
      this.editPosts = item;
    },
    // 点击修改
    async edit(edit){
      this.deitFormVisible = false;
      console.log("已修改");
      console.log(edit);
      edit = JSON.stringify(edit)
      const {data:res} = await this.$http.post("editPosts",{edit});
      console.log(res);
      if(res.status != 200){
        this.$message.error("修改信息失败");
      }else{
        this.$message({
          message: '修改成功',
          type: 'success'
        });
        this.getPostsList();
      }

    },
    // 删除部分
    handleClose(done){
      // this.$confirm('确定关闭？').then(_ => {
      //   done();
      // }).catch(_ => {})
    },
    async del(id) {
      this.dialogVisible = false;
      console.log("删除了");
      console.log(id);
      const {data:res} = await this.$http.post("delPosts",{id});
      // // console.log(result);
      if(res.status !==200){
        return this.$message.error("添加失败")
      }else{
        this.$message.success("删除成功")
        this.getPostsList();
      }

    }
  }
}
</script>
<style scoped>
.el-select .el-input {
  width: 130px;
}
.input-with-select .el-input-group__prepend {
  background-color: #fff;
  /* width: 150px; */
}
.box-card {
  margin: 10px 0;
}
.el-button {
  margin: 0;
}
.el-table {
  margin: 10px 0;
}
</style>
